#coding=utf-8

import urllib2
import hashlib
import json

api_base_url = "http://192.168.25.1:8888/mapi"

username = "goalzz"
password = "851100"

tokenValue = "y6i573pE6fJlS6OO8dxLqKFrPgM9KMvW"
key = "lWGiqLbOGcGf1IR6fz3Wsesvj9CWX3e9"



def sign(key, token, params_str):
    for_sign_str = params_str + token + key
    print for_sign_str

    return hashlib.md5(for_sign_str).hexdigest()

def params_to_json(params):
    if len(params) == 0:
        return ""
    else:
        return json.dumps(params)

def request(url, post_data, token, sign_str):
    post_data = params_to_json(post_data)
    req = urllib2.Request(url, post_data)
    req.add_header("Token", token)
    req.add_header("Md5", sign_str)

    print sign_str

    response = urllib2.urlopen(req)
    return response.read()

def request_login(username, password):
    global api_base_url
    login_data = {"username":username, "password":password, "device_data":{"os":"android","version":"1.2.1"}}
    req = urllib2.Request(api_base_url + "/login", params_to_json(login_data))
    response = urllib2.urlopen(req)
    return response.read()


#自动登录一次然后再请求真正数据
def auto_login_request(url, post_data):
    global username, password
    login_rep = request_login(username, password)
    print login_rep
    json_obj = json.loads(login_rep)

    token = json_obj["data"]["token"]
    key = json_obj["data"]["key"]
    sign_str = sign(key, token, params_to_json(post_data))
    try:
        return request(url, post_data, token, sign_str)
    except Exception,e:
        print e
        return e.read()

#登录一次试试
#print request_login(username, password)

#获取warning数据

j = auto_login_request(api_base_url + "/warning/list", {"offset":0, "size":30})
print j
#print json.loads(j)["data"]["tracings"]["2"]["Title"]

#j = auto_login_request(api_base_url + "/warning/detail", {"warning_id":7})
#print j
#print json.loads(j)["data"]["tracings"]["2"]["Title"]


